package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 根据文章id 查询作者详情
 */
@WebServlet("/getuserbyaid")
public class GetUserByAid extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       String msg="未知错误！";
        UserInfo userInfo=new UserInfo();
        //1.得到前端的参数并校验
        String aidStr=req.getParameter("aid");
        if(!StrUtil.isBlank(aidStr)){//非null非“”
            int aid=Integer.valueOf(aidStr);
            if(aid>0){
                //2.查询数据库并组织返回的数据
                Connection connection= DBUtils.getConnection();
                String sql=" select * from userinfo where uid=(select uid from article where aid=?)";
                PreparedStatement statement= connection.prepareStatement(sql);
                statement.setInt(1,aid);
                ResultSet resultSet=statement.executeQuery();
                if(resultSet.next()){
                    userInfo.setUid(resultSet.getInt("uid"));
                    userInfo.setUsername(resultSet.getString("username"));
                    userInfo.setImg(resultSet.getString("img"));
                }
                //查询用户发表的所有的文章数
                sql=" select count(*) as acount from article where uid=(select uid from article where aid=?)";
                PreparedStatement statement1= connection.prepareStatement(sql);
                statement1.setInt(1,aid);
                ResultSet resultSet1=statement1.executeQuery();
                if(resultSet1.next()){
                    userInfo.setAcount(resultSet1.getInt("acount"));
                } msg="";
                //关闭资源
                DBUtils.close(resultSet1,statement1,null);
                DBUtils.close(resultSet,statement,connection);
            }else{
                msg="非法错误";
            }
        }else{
            msg="非法参数";
        }
        //3.将上面的数据返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtil.toResult(
                200,userInfo,msg)));
    }
}
